/*! Omvandla.h*/
#pragma once

#include <iostream>
#include <string>
#include <iomanip>
#include <stdlib.h>

using namespace std;

class Omvandlare : Bitstr
{
public:
	/*! Empty constructor */
	Omvandlare(void) {}
	/*! Empty destructor */
	~Omvandlare(void) {}
	/* Converts an integer to a binary string */
	void convertDecToBin(int tal, string &str)
	{
		char buf[10];
		if(tal == 0)
			return;
		else
		{
			int result = tal/2;
			int carry = tal%2;
			string carryString = itoa(carry, buf, 10);
			str.insert(0, carryString);
			convertDecToBin(result, str);
		}
	}

	/* Converts a binary string to an integer, can also handle negatives */
	int convertBinToDec(string str)
	{
		bool negative = false;
		if( str[0] == '1')
		{
			twoComplement(str);
			negative = true;
		}
		char buf[10];
		int g;
		int sum = 0;
		int k = 0;

		for(int i = str.length()-1; i <= str.length(); i--)
		{
			char c = str[i];
			g = (c) - 48;
			sum += g * pow(2,k);
			k++;
		}
		if(negative)
			return -sum;
		else
			return sum;
	}

	/*! Handles functioncalls for the convertfunctions if the integer is negative. Also creates the string with nrbits bits */
	string tal_str(int tal, string &str, int nrbits)
	{
		if (tal > 0)
		{
			convertDecToBin(tal, str);
			int str_len = str.length();
			if( str_len > nrbits)
			{
				str.erase(0, str_len - nrbits);
			}
			else
			{
				for(int i = 0; i < nrbits - str_len; i++)
				{
					str.insert(0, "0");
				}
			}
		}
		else
		{
			int negativt_tal = abs(tal);
			convertDecToBin(negativt_tal, str);
			int str_len = str.length();
			if( str_len > nrbits)
			{
				str.erase(0, str_len - nrbits);
			}
			else
			{
				for(int i = 0; i < nrbits - str_len; i++)
				{
					str.insert(0, "0");
				}
			}
			twoComplement(str);
			return str;
		}
		return str;
	}
};
